﻿namespace Microsoft.Web.Helpers.Tests
{
    using System;
    using System.Data.Services;
    using System.Data.Services.Providers;
    using System.IO;

    public class MockStreamProvider : IDataServiceStreamProvider
    {
        public int StreamBufferSize
        {
            // Use a buffer size of 64K bytes.
            get { return 64000; }
        }

        public void DeleteStream(object entity, DataServiceOperationContext operationContext)
        {
            throw new NotImplementedException();
        }

        public System.IO.Stream GetReadStream(object entity, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
        {
            throw new NotImplementedException();
        }

        public Uri GetReadStreamUri(object entity, DataServiceOperationContext operationContext)
        {
            return null;
        }

        public string GetStreamContentType(object entity, DataServiceOperationContext operationContext)
        {
            return "image/jpg";
        }

        public string GetStreamETag(object entity, DataServiceOperationContext operationContext)
        {
            return null;
        }

        public System.IO.Stream GetWriteStream(object entity, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
        {
            if (checkETagForEquality != null)
            {
                // this stream provider implementation does not support ETags associated with BLOBs
                throw new DataServiceException(400, "This demo does not support ETags associated with BLOBs");
            }

            Image entry = entity as Image;

            if (entry == null)
            {
                throw new DataServiceException(500, "Internal Server Error: " + "the Media Link Entry could not be determined.");
            }

            // Return the filestream that the data service uses to 
            // write the requested binary data stream to a temp file.
            string binaryFile = "uploaded-image.jpg";
            return new FileStream(binaryFile, FileMode.Create, FileAccess.ReadWrite);
        }

        public string ResolveType(string entitySetName, DataServiceOperationContext operationContext)
        {
            if (entitySetName == "Products")
            {
                return "Microsoft.Samples.Razor.Helpers.Tests.Product";
            }
            else if (entitySetName == "Images")
            {
                return "Microsoft.Samples.Razor.Helpers.Tests.Image";
            }
            else
            {
                // This will raise an DataServiceException.
                return null;
            }
        }
    }
}
